<template>
	<el-select popper-class="select-popper" :popper-append-to-body="popperAppendToBody" filterable :multiple="multiple" v-model="viewModel" class="x-select" placeholder="请选择" :size="size" v-if="keyValues">
		<el-option v-for="item in keyValues" :key="item.key" :value="item.key" :label="item.value"></el-option>
	</el-select>
</template>

<script>
	import api from 'api'
	import ala from 'ala'
	export default {
		model: {
			prop: 'dataModel',
			event: 'change'
		},
		props: {
			type: {},
			size: {},
			noChoice: {
				default: false
			},
			multiple: {
				default: false
			},
			apiUrl: {}, // Api网址，优先从Api中获取数据
			dataModel: {},
			popperAppendToBody: {
				default: true
			}
		},
		data() {
			return {
				keyValues: null,
				viewModel: 0
			}
		},
		mounted() {
			this.init()
		},
		methods: {
			async init() {
				if (this.keyValues === null) {
					this.keyValues = await api.typeKeyValues(this.type, this.apiUrl)
					if (this.noChoice === true) {
						var para = {
							key: '',
							value: '请选择'
						}
						this.keyValues.unshift(para)
					}
				}
				if (this.keyValues) {
					var find = this.keyValues.find(r => r.key === this.dataModel)
					if (!find && this.keyValues.length > 0) {
						this.viewModel = this.keyValues[0].key
						return
					}
				}
				this.viewModel = this.dataModel
			}
		},
		watch: {
			viewModel: {
				deep: true,
				handler(val) {
					this.$emit('change', this.viewModel)
				}
			}
		}
	}
</script>